package com.shizhen.aidemo.controller;

import com.shizhen.aidemo.config.ChatRedisMemory;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RequiredArgsConstructor
@RestController
@RequestMapping("/ai")
public class ChatController {

    private final ChatClient chatClient;
    private final ChatRedisMemory chatRedisMemory;

    @RequestMapping(value = "/chat", produces = "text/html; charset=utf-8")
    public Flux<String> chat(String prompt,String chatId) {
        return chatClient
                .prompt()
                .user(prompt)
                .advisors(a -> a.param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY,chatId))
                .stream()
                .content();
    }

    //redis持久化聊天
    @RequestMapping(value = "/redisChat", produces = "text/html; charset=utf-8")
    public Flux<String> redisChat(@RequestParam(value = "message",defaultValue = "讲个笑话") String message, @RequestParam String sessionId) {
        return chatClient.prompt()
                .user(message)
                .advisors(new MessageChatMemoryAdvisor(chatRedisMemory,sessionId,10))
                .stream()
                .content();
    }
}
